<template>
  <a-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :bodyStyle="bodyStyle"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
    wrapClassName="ant-modal-cust-warp"
    style="top:15%;height: 70%;overflow-y: hidden"
  >
    <template slot="footer">
      <a-button key="back" v-if="isReadOnly" @click="handleCancel">
        关闭
      </a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" id="customerModal">
        <a-row>
          <a-col :span="12">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="客户名称">
              <a-input disabled placeholder="请输入客户名称" v-decorator.trim="['customerName', validatorRules.name]" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="内部编码">
              <a-input disabled placeholder="请输入内部编码" v-decorator.trim="['contractCode', validatorRules.name]" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="合同号">
              <a-input disabled placeholder="请输入合同号" v-decorator.trim="['contractNum', validatorRules.name]" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="合同表id">
              <a-input disabled placeholder="请输入合同表id" v-decorator.trim="['contractId', validatorRules.name]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-divider>产品详情添加</a-divider>
          <a-col :span="24 / 3">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="产品名称">
              <a-input placeholder="请输入产品名" v-model="name" />
            </a-form-item>
          </a-col>
          <a-col :span="24 / 3">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="产品单位">
              <a-input placeholder="请输入产品单位" v-model="unit" />
            </a-form-item>
          </a-col>
          <a-col :span="24 / 3">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="数量">
              <!-- <a-input placeholder="请输入数量" v-model="count" /> -->
              <a-input-number style="width:100%;" placeholder="请输入数量" v-model="count" :min="1" />
            </a-form-item>
          </a-col>
          <!-- <a-col :span="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="规格展示">
              {{
                newMapObject
                  ? newMapObject
                      .split('{')
                      .join('')
                      .split('}')
                      .join('')
                      .split('"')
                      .join('')
                  : '可添加多个'
              }}
            </a-form-item>
          </a-col> -->
          <a-col :span="24 / 3">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="规格">
              <a-input placeholder="请输入" v-model="specification" />
            </a-form-item>
          </a-col>
          <a-col :span="24 / 3">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="批次">
              <a-input placeholder="请输入" v-model="batch" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <!-- <a-button @click="addNewModel()" type="primary">添加规格属性</a-button> -->
            <!-- <a-divider type="vertical" /> -->
            <a-button @click="addList" type="primary" style="margin:10px 0px">添加</a-button>
          </a-col>
          <!-- <a-divider>产品详情</a-divider> -->
        </a-row>
        <div>
          <a-table ref="table" size="middle" bordered rowKey="id" :columns="columns" :dataSource="dataSource">
            <template
              v-for="col in ['productName', 'specification', 'count', 'unit', 'batch']"
              :slot="col"
              slot-scope="text, record, index"
            >
              <div :key="col">
                <a-input
                  v-if="record.editable"
                  style="margin: -5px 0"
                  :value="text"
                  @change="e => myhandleChange(e.target.value, record, col)"
                />
                <template v-else>
                  {{ text }}
                </template>
              </div>
            </template>
            <!-- 操作 -->
            <span slot="action" slot-scope="text, record, index">
              <span class="editable-row-operations">
                <span v-if="record.editable">
                  <a @click="() => save(record)">保存</a>
                </span>
                <span v-else>
                  <a :disabled="editingKey !== ''" @click="() => Listedit(record)">编辑</a>
                </span>
              </span>
              <a-divider type="vertical" />
              <span>
                <a-popconfirm title="确定删除吗?" @confirm="() => Delete(record)">
                  <a>删除</a>
                </a-popconfirm>
              </span>
            </span>
          </a-table>
        </div>
        <!-- <a-col :span="12">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="产品名称">
            <a-input placeholder="请输入规格" v-decorator.trim="['productName', validatorRules.name]" />
            <a-select
              v-decorator.trim="['productName', validatorRules.name]"
              allowClear
              placeholder="选择"
              showSearch
              @change="handleChangeProduct"
              optionFilterProp="children"
            >
              <a-select-option v-for="(item, index) in PraductNameList" :key="index" :value="item.name">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col> -->
        <!-- <a-col :span="12">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="规格">
            <a-input placeholder="请输入规格" v-decorator.trim="['specification']" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="产品单位">
            <a-input placeholder="请输入产品单位" v-decorator.trim="['unit']" />
          </a-form-item>
        </a-col> -->
        <!-- <a-col :span="12">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="批次">
            <a-input placeholder="请输入批次" v-decorator.trim="['batch']" />
          </a-form-item>
        </a-col> -->
        <!-- <a-col :span="12">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="数量">
            <a-input-number style="width:100%;" placeholder="请输入数量" v-decorator.trim="['count']" :min="1" />
          </a-form-item>
        </a-col> -->
        <a-col :span="12">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="物流单号">
            <a-input placeholder="请输入物流单号" v-decorator.trim="['logisticsNum']" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="发货日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-date-picker
              style="width: 100%"
              v-decorator.trim="['sendOutDate']"
              format="YYYY-MM-DD"
              placeholder="请输入发货日期"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="发货单文件">
            <div :key="Math.random()">
              <a-upload
                name="file"
                accept=".txt,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf"
                :beforeUpload="beforeUpload"
                :showUploadList="false"
                :multiple="false"
                :headers="tokenHeader"
                :action="importExcelUrl"
                @change="myhandleImportExcel"
              >
                <a-button><a-icon type="upload" />上传</a-button>
              </a-upload>
            </div>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="回执单">
            <div :key="Math.random()">
              <a-upload
                name="file"
                accept=".txt,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf"
                :beforeUpload="beforeUpload"
                :showUploadList="false"
                :multiple="false"
                :headers="tokenHeader"
                :action="importExcelUrlT"
                @change="myhandleImportExcelT"
              >
                <a-button><a-icon type="upload" />上传</a-button>
              </a-upload>
            </div>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="收货回执">
            <a-select
              v-decorator.trim="['status']"
              allowClear
              placeholder="选择"
              showSearch
              @change="handleChange"
              optionFilterProp="children"
            >
              <a-select-option v-for="(item, index) in Receipt" :key="index" :value="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="isShow">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="批注">
            <a-input placeholder="请输入" v-decorator.trim="['notation']" />
          </a-form-item>
        </a-col>
      </a-form>
    </a-spin>
  </a-modal>
</template>
<script>
import pick from 'lodash.pick'
import { addContractLogistics, checkSupplier } from '@/api/api'
import { autoJumpNextInput } from '@/utils/util'
import Vue from 'vue'
import { getAction } from '@/api/manage'
import { ACCESS_TOKEN } from '@/store/mutation-types'
export default {
  name: 'AddLogistics',
  data() {
    return {
      title: '操作',
      Receipt: [
        { id: 0, name: '未收' },
        { id: 1, name: '已收' },
        { id: 2, name: '未收特批' }
      ],
      tokenHeader: { Authorization: 'Bearer ' + Vue.ls.get(ACCESS_TOKEN) },
      isShow: false,
      visible: false,
      bodyStyle: {
        padding: '20',
        height: window.innerHeight * 0.5 + 'px',
        'overflow-y': 'auto'
      },
      model: {},
      record: null,
      isReadOnly: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      PraductNameList: [],
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      defaultFileListO: null,
      defaultFileListT: null,
      url: {
        lists: '/contractProduct/getList',
        importExcelUrl: '/systemConfig/upload' + '?' + `biz=fh`,
        importExcelUrlT: '/systemConfig/upload' + '?' + `biz=hz`
      },
      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        name: {
          rules: [{ required: true, message: '请输入!' }]
        }
      },
      cacheData: [],
      dataSource: [],
      columns: [
        { title: '产品名称', dataIndex: 'productName', width: 80, scopedSlots: { customRender: 'productName' } },
        { title: '规格', dataIndex: 'specification', width: 80, scopedSlots: { customRender: 'specification' } },
        { title: '单位', dataIndex: 'unit', width: 80, scopedSlots: { customRender: 'unit' } },
        { title: '数量', dataIndex: 'count', width: 80, scopedSlots: { customRender: 'count' } },
        { title: '批次', dataIndex: 'batch', width: 80, scopedSlots: { customRender: 'batch' } },
        {
          title: '操作',
          dataIndex: 'action',
          width: 80,
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      guiG: null,
      guiGvalue: null,
      key: new Date().getTime(),
      name: '',
      count: '',
      unit: '',
      batch: '',
      specification: '',
      editingKey: ''
    }
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}${this.url.importExcelUrl}`
      // return `api${this.url.importExcelUrl}`
    },
    importExcelUrlT: function() {
      return `${window._CONFIG['domianURL']}${this.url.importExcelUrlT}`
      // return `api${this.url.importExcelUrl}`
    }
  },
  mounted() {
    this.cacheData = this.dataSource.map(item => ({ ...item }))
  },
  methods: {
    myhandleChange(value, record, column) {
      const newData = [...this.dataSource]
      if (record.key) {
        var target = newData.find(item => record.key === item.key)
      } else {
        var target = newData.find(item => record.id === item.id)
      }
      if (target) {
        target[column] = value
        this.dataSource = newData
      }
    },
    save(record) {
      const newData = [...this.dataSource]
      if (record.key) {
        var target = newData.find(item => record.key === item.key)
      } else {
        var target = newData.find(item => record.id === item.id)
      }
      this.editingKey = ''
      if (target) {
        Object.assign(
          target,
          record.key
            ? this.cacheData.find(item => record.key === item.key)
            : this.cacheData.find(item => record.id === item.id)
        )
        delete target.editable
        this.dataSource = newData
      }
    },
    Listedit(record) {
      const newData = [...this.dataSource]
      if (record.key) {
        var target = newData.find(item => record.key === item.key)
      } else {
        var target = newData.find(item => record.id === item.id)
      }

      this.editingKey = record.key ? record.key : record.id
      if (target) {
        target.editable = true
        this.dataSource = newData
      }
    },
    //添加产品List
    addList() {
      if (this.name && this.unit && this.specification && this.count && this.batch) {
        this.dataSource.push({
          key: new Date().getTime(),
          productName: this.name,
          unit: this.unit,
          batch: this.batch,
          specification: this.specification,
          // ? this.newMapObject
          //     .split('{')
          //     .join('')
          //     .split('}')
          //     .join('')
          //     .split('"')
          //     .join('')
          // : this.newMapObject,
          count: this.count
        })
        // this.key++
        this.name = null
        this.unit = null
        this.specification = null
        this.count = null
        // this.vaArr = []
        this.batch = ''
      } else {
        this.$message.warning('请填写完整信息！')
        return
      }
    },
    //删除产品List
    Delete(record) {
      console.log(record)
      //根据key，id判断删除dom还是接口删除
      if (record.key) {
        console.log('dom删')
        let key = record.key
        const dataSource = [...this.dataSource]
        this.dataSource = dataSource.filter(item => item.key !== key)
      } else if (record.id) {
        deleteAction(this.url.delete, { id: record.id }).then(res => {
          if (res.code === 200 || res.code === 10000) {
            let id = record.id
            const dataSource = [...this.dataSource]
            this.dataSource = dataSource.filter(item => item.id !== id)
            // this.getTableList(record)
          } else {
            that.$message.warning(res.data.message)
          }
        })
      }
    },
    moted() {
      let params = {
        contractCode: this.model.contractCode
      }
      console.log(params, 'params')
      getAction(this.url.lists, params).then(res => {
        if (res.code === 200 || res.code === 10000) {
          this.PraductNameList = res.data
        }
      })
    },
    //图片上传前做限制
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        //文件名后缀
        let hz = file.name.substring(file.name.lastIndexOf('.'))
        let isType = ['.xlsx', '.doc', '.txt', '.docx', '.xls', '.ppt', '.pptx', '.pdf'].includes(hz)
        if (!isType) {
          this.$message.error('格式错误,只能上传.xlsx、.doc、.txt、.docx、.xls、.ppt、.pptx、.pdf')
          return reject(false)
        }
        return resolve(true)
      })
    },
    //选择产品带入规格信息
    handleChangeProduct(value) {
      this.PraductNameList.map(item => {
        if (item.name == value) {
          this.form.setFieldsValue({ specification: item.specification })
          this.form.setFieldsValue({ unit: item.unit })
        }
      })
    },
    /* 导入 */
    myhandleImportExcel(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        if (info.file.response) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 200 || info.file.response.code === 10000) {
            this.$message.success(`${info.file.name} 文件上传成功` || info.file.response.data)
            this.defaultFileListO = info.file.response.data
          } else {
            this.$message.warning(info.file.response.message)
          }
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.data}.`)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`文件上传失败: ${info.file.msg} `)
      }
    },
    /* 导入 */
    myhandleImportExcelT(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        if (info.file.response) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 200 || info.file.response.code === 10000) {
            this.$message.success(`${info.file.name} 文件上传成功` || info.file.response.data)
            this.defaultFileListT = info.file.response.data
          } else {
            this.$message.warning(info.file.response.message)
          }
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.data}.`)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`文件上传失败: ${info.file.msg} `)
      }
    },
    handleChange(value) {
      if (value == 2) {
        this.isShow = true
      } else {
        this.isShow = false
      }
      console.log(value)
    },
    add(record) {
      this.record = record
      this.edit(record)
      console.log(record, 'recordrecord')
    },
    edit(record) {
      //如果数组内有旧数据值则清空
      this.defaultFileListT = this.model.shippingReceipts
      this.defaultFileListO = this.model.shippingOrder
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.moted()
      this.visible = true
      this.$nextTick(() => {
        //编辑
        if (record.batch) {
          this.dataSource = JSON.parse(this.model.products)
          var sendOutDate = this.$moment(this.model.sendOutDate)
          this.form.setFieldsValue({ sendOutDate: sendOutDate })
          this.form.setFieldsValue({ specification: this.model.specification })
          this.form.setFieldsValue({ unit: this.model.unit })
          this.form.setFieldsValue({ batch: this.model.batch })
          this.form.setFieldsValue({ count: this.model.count })
          this.form.setFieldsValue({ logisticsNum: this.model.logisticsNum })
          this.form.setFieldsValue({ contractId: this.model.contractId })
          // let Status
          // this.Receipt.forEach(item => {
          //   item.id == this.model.status ? (Status = item.name) : ''
          // })
          this.form.setFieldsValue({ status: Number(this.model.status) })
        } else {
          //新增
          this.form.setFieldsValue({ contractId: this.record.id })
        }
        if (this.model.status == 2) {
          this.isShow = true
          setTimeout(() => {
            this.form.setFieldsValue({ notation: this.model.notation })
          }, 300)
        } else {
          this.isShow = false
        }
        this.form.setFieldsValue(
          pick(
            this.model,
            'contractCode',
            'contractNum',
            'customerName',
            'productName',
            'shippingOrder',
            'shippingReceipts'
          )
        )
        autoJumpNextInput('customerModal')
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let formData = Object.assign(values)
          if (this.model.beginNeedGet && this.model.beginNeedPay) {
            that.$message.warn('期初应收和期初应付不能同时输入')
            that.confirmLoading = false
            return
          }
          if (this.dataSource.length == 0) {
            this.$message.warning('请添加产品详情!')
            that.confirmLoading = false
            return
          }
          //编辑
          if (this.model.batch) {
            formData.id = this.model.id
          } else {
            formData.contractId = this.record.id
          }
          formData.products = JSON.stringify(this.dataSource)
          formData.shippingOrder = this.defaultFileListO
          formData.shippingReceipts = this.defaultFileListT
          formData.contractCode = this.model.contractCode
          formData.contractNum = this.model.contractNum
          formData.customerName = this.model.customerName
          formData.sendOutDate = this.$moment(formData.sendOutDate).format('YYYY-MM-DD')
          let obj
          if (!this.model.id) {
            obj = addContractLogistics(formData)
          } else {
            obj = addContractLogistics(formData)
          }
          obj
            .then(res => {
              if (res.code === 200 || res.code === 10000) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
              that.close()
            })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    validateSupplierName(rule, value, callback) {
      let params = {
        name: value,
        type: '客户',
        id: this.model.id ? this.model.id : 0
      }
      checkSupplier(params).then(res => {
        if (res && res.code === 200) {
          if (!res.data.status) {
            callback()
          } else {
            callback('名称已经存在')
          }
        } else {
          callback(res.data)
        }
      })
    }
  }
}
</script>
<style scoped>
/** Button按钮间距 */
.table-operator .ant-btn {
  margin: 0 8px 8px 0;
}
@import '~@assets/less/common.less';
</style>
